﻿using AutoMapper;
using MediatR;
using NPOI.SS.Formula.Functions;
using ProcurementManagement.Applcation.Command.PurchaseContractsCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.PurchaseContractsCommandHandler
{
    public class PurchaseContractsUpdCommandHandler:IRequestHandler<PurchaseContractsUpdCommand,int>
    {
        private readonly IPurchaseContractsRepository _purchaseContractsRep;
        private readonly ISourcProductContractRepository _sourceProductContractRep;
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;
        public PurchaseContractsUpdCommandHandler(IPurchaseContractsRepository purchaseContractsRep, ISourcProductContractRepository sourceProductContractRep, ISqlSugarClient db, IMapper mapper)
        {
            this._purchaseContractsRep = purchaseContractsRep;
            this._sourceProductContractRep = sourceProductContractRep;
            this.db = db;
            this._mapper = mapper;
        }

        public async Task<int> Handle(PurchaseContractsUpdCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                //修改采购退货
                var se = await db.Queryable<PurchaseContracts>()
                                 .Where(c => c.PurchaseContractsIds == request.UpdDTO.PurchaseContractsIds)
                .FirstAsync();

                var procurement1 = _mapper.Map<PurchaseContracts>(request.UpdDTO);
                var taskToAdd = await _purchaseContractsRep.UpdataAsync(procurement1);


                //删除采购退货中的数据
                var itemsToDelete = await db.Queryable<SourcProductContract>()
                                  .Where(c => c.PCNumber == se.PCNumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await _sourceProductContractRep.DelRange(new List<SourcProductContract> { item });
                }

                // 假设需要插入相关的产品合同
                foreach (var item in request.UpdDTO.upddtos)
                {
                    SourcProductContract detail = new SourcProductContract();
                    detail.ProductId = item.ProductId;
                    detail.SPCNum = item.SPCNum;
                        detail.SPCPrice = item.SPCPrice;
                    detail.SPCDocumentsType = item.SPCDocumentsType;
                    detail.SPCTotalPrice = item.SPCTotalPrice;
                    detail.SPCAfterPrice = item.SPCAfterPrice;
                    detail.SPCAfterTotalPrice = item.SPCAfterTotalPrice;
                    detail.SPCArrivalDate = item.SPCArrivalDate;
                    detail.PCNumber = procurement1.PCNumber;
                    detail.SPCRemark = item.SPCRemark;
                    detail.SPPNumber = item.SPPNumber;
                    detail.SPPName = item.SPPName;
                    detail.SPPSpec = item.SPPSpec;
                    detail.Office_Id = item.Office_Id;
                    detail.User_Id = item.User_Id;

                    await _sourceProductContractRep.AddAsync(detail);
                }

                // 提交事务
                db.Ado.CommitTran();

                return 1; // 返回插入的合同 ID
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
